package com.student_exam_system.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.student_exam_system.Util.JwtUtil;
import com.student_exam_system.config.ConstMsg;
import com.student_exam_system.pojo.Answer;
import com.student_exam_system.pojo.AnswerCards;
import com.student_exam_system.service.AnswerService;
import com.student_exam_system.service.PaperQuestionService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fire'ge
 */
@Controller
@RequestMapping(value = "/answer")
public class AnswerController {
    private final AnswerService answerService;
    private final PaperQuestionService paperQuestionService;
    List<Answer> answers;
    Map<String,List<Answer>> answersMap = new HashMap<>(100);


    public AnswerController(@Qualifier("answerServiceImpl") AnswerService answerService
            ,@Qualifier("paperQuestionServiceImpl") PaperQuestionService paperQuestionService) {
        this.answerService = answerService;
        this.paperQuestionService = paperQuestionService;
    }

    @PreAuthorize("hasAuthority('student')")
    @RequestMapping(value = "/addToList/{paperListId}/{answer}",produces = "application/json;charset=utf-8")
    public String addToList(@PathVariable int paperListId,
                            @PathVariable String answer, HttpServletRequest request) {


        String token = request.getHeader("token");
        int jwtUserId = JwtUtil.getJWTUserId(token);
        int paperId = (int)request.getSession().getAttribute("paperId");
        request.setAttribute("paperListId",paperListId+1);

        if (answersMap.containsKey(ConstMsg.CONTAIN_MAP_KEY +jwtUserId+ paperId)){
            answers = answersMap.get(ConstMsg.CONTAIN_MAP_KEY  + jwtUserId+ paperId);
        }
        else{
            answers = new ArrayList<>();
            answersMap.put(ConstMsg.CONTAIN_MAP_KEY+jwtUserId+paperId,answers);
        }
        int questionId = (int)request.getSession().getAttribute("questionId");
        int pqId = paperQuestionService.getPqId(paperId, questionId);
        answers.add(new Answer(0,jwtUserId,answer,0,pqId));

        return "forward:/answer/addToDB";
    }

    @PreAuthorize("hasAuthority('student')")
    @RequestMapping(value = "/addToDB",produces ="application/json;charset=utf-8")
    public ModelAndView addToDb(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        for (List<Answer> a:answersMap.values()) {
            int insert = answerService.addMulAnswer(a);
            if(insert < a.size()){
                throw new RuntimeException("部分提交试卷失败，有"+(a.size()-insert)+"道题提交失败");
            }
        }
        Object newPaperListId = request.getAttribute("paperListId");
        mv.setViewName("forward:/question/showQueData?paperListId="+newPaperListId);
        return mv;
    }

    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    @RequestMapping(value = "/queryAnswerCard/{paperId}",produces = "application/json;charset=utf-8")
    public String queryAnswerCards(@PathVariable int paperId, HttpServletRequest request) {
        String token = request.getHeader("token");
        int jwtUserId = JwtUtil.getJWTUserId(token);
        List<AnswerCards> answerCards = answerService.queryAnswerCard(jwtUserId, paperId);
        System.out.println(answerCards);

        return JSON.toJSONString(answerCards);
    }
    @PreAuthorize("hasAuthority('teacher')")
    @RequestMapping("/answerList/{paperId}/{questionId}/{teacherId}")
    @ResponseBody
    public String answerList(@PathVariable int paperId, @PathVariable int questionId, @PathVariable int teacherId){
        List<Answer> answers = answerService.answerList(paperId, questionId, teacherId);
        ObjectMapper objectMapper = new ObjectMapper();
        String json=null;
        try {
            json = objectMapper.writeValueAsString(answers);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @PreAuthorize("hasAuthority('teacher')")
    @RequestMapping("/giveMark/{choice}/{point}/{studentId}/{paperId}/{questionId}")
    @ResponseBody
    public int giveMark(@PathVariable int choice,@PathVariable double point,@PathVariable int studentId,@PathVariable int paperId,@PathVariable int questionId){
        return answerService.giveMark(choice, point, studentId, paperId, questionId);
    }
}
